package org.jimmy.tang.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * @author jimmy
 * 
 */
public class FileDemo {

    public static void main(String[] args) throws FileNotFoundException {
        testPrintWriter();
        testBufferedReader();
    }

    private static void testPrintWriter() throws FileNotFoundException {
        Scanner in = new Scanner(new File("/home/jimmy/Documents/test.txt"));
        PrintWriter pw = new PrintWriter(new File(
                "/home/jimmy/Documents/test1.txt"));
        String name = "GinSmile";
        pw.write(name);// 把字符串添加到文件末尾
        pw.append('w');// 直接把字符添加到文件末尾
        pw.println();// 仅仅打印一个换行符
        while (in.hasNext()) {
            String s = in.nextLine();
            pw.println(s);
        }

        pw.println();
        pw.printf("%x", 100);
        pw.println();
        char[] buf = { 'a', 'b', 'c', 'd', 'e', 'f' };
        pw.write(buf, 0, 4);// 把字符数组的一部分添加到文件末尾

        pw.close();
    }

    /**
     * 
     * @throws FileNotFoundException
     */
    private static void testBufferedReader() throws FileNotFoundException {
        File file = new File("/home/jimmy/Documents/test1.txt");
        String s;
        BufferedReader br = new BufferedReader(new FileReader(file));
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(
                    "/home/jimmy/Documents/test2.txt"));
            while ((s = br.readLine()) != null) {
                bw.write(s);
                bw.newLine();
                bw.flush();
                bw.write("GinSmile");
                bw.newLine();
            }
        } catch (IOException e) {

            e.printStackTrace();
        }

    }
}
